'use strict';

const Controller = require('egg').Controller;
const _ = require('lodash');

const MongoObjectIdSchema = {
  type: 'string',
  max: 24,
  min: 24,
};

class CollectApi extends Controller {
  /**
   * 通过插件分享
   * title: 标题,
   * content: 内容,
   * tab: 分享到哪个版块,
   * original_url: 原始链接,
   * is_public: 是否公开,
   * collect_tags: 标签array
   */
  async share() {
    const {ctx, service} = this;
    const body = ctx.request.body;

    const user_id = ctx.request.user.id;
    const collect_tags = body.collect_tags;
    const brief = body.brief.trim();
    const title = body.title.trim();
    const content = body.content.trim();
    const original_url = body.original_url;
    const tab = body.tab;
    let is_public = body.is_public;
    let topic_id = body.topic_id;


    // topic_id不存在 代表是新增
    if (!topic_id) {
      let topic = null;
      // 如果是站内文章
      if (/\/topic\/\w{24}$/.test(original_url)) {
        topic = await ctx.model.Topic.findOne({_id: original_url.substr(-24)});
        if (!topic) {
          ctx.body = {status: 'failed'};
          return;
        }
        is_public = topic.is_public;
      } else {
        // 储存新文章
        topic = await service.topicSvc.newAndSave(title, content, tab, user_id, original_url, is_public, undefined, undefined, brief);
      }

      topic_id = topic._id;

      await Promise.all([
        service.topicCollectSvc.upsert(user_id, topic_id, title, brief, is_public, original_url, collect_tags),
        service.userSvc.incrementCollectTopicCount(user_id),
        service.topicSvc.incrementCollectCount(topic_id),
        service.userSvc.incrementScoreAndTopicCount(topic.author_id, 3, 0),
      ]);
    } else {
      // 修改的情况
      await Promise.all([
        ctx.model.Topic.updateOne({original_url: original_url, author_id: user_id}, {
          $set: {
            title, is_public, intro: brief
          }
        }),
        service.topicCollectSvc.upsert(user_id, topic_id, title, brief, is_public, original_url, collect_tags)
      ]);
    }


    await this.ctx.helper.notifySuperAdmin(user_id, topic_id);


    ctx.body = {
      status: 'success',
      topic_id: topic_id,
    };
  }


  /**
   * 通过插件取消分享
   * topic_id: 要取消收藏的文章id,
   * content: 内容,
   * tab: 分享到哪个版块,
   * original_url: 原始链接,
   * is_public: 是否公开,
   * collect_tags: 标签array
   */
  async cancel_share() {
    const {ctx, service} = this;
    const user_id = ctx.request.user.id;
    const topic_id = ctx.request.body.topic_id;

    // 删除话题, 话题作者topic_count减1
    // 删除回复，回复作者reply_count减1
    // 删除topic_collect，用户collect_topic_count减1
    // collect_tags表里, topic_ids去除topic_id
    const [topic, author] = await service.topicSvc.getFullTopic(topic_id);

    if (!topic) {
      ctx.status = 422;
      ctx.body = {message: '此话题不存在或已被删除。', success: false};
      return;
    }

    if (topic.author_id != user_id) {
      ctx.status = 403;
      ctx.body = {message: '无权限', success: false};
      return;
    }

    if (topic.tab == 'share') {
      author.score -= 3;
    } else {
      author.score -= 5;
      author.topic_count -= 1;
    }

    await author.save();

    await topic.remove();

    // 删除文章的同时, 把收藏也要删了
    let collectUsers = await service.topicCollectSvc.getCollectUsersByTopicId(topic_id);
    for (let collectUser of collectUsers) {
      const user = await service.userSvc.getUserById(collectUser.user_id);
      user.collect_topic_count -= 1;
      await user.save();
    }
    await service.topicCollectSvc.removeAllUserCollect(topic_id);


    ctx.body = {
      status: 'success'
    };
  }


  /**
   * 展示用户所有标签及标签包含文章的数量
   * user_id: 用户id
   * tag_name: 可以按照标签名字模糊搜索
   */
  async listTags() {
    console.time('listTags');
    const {ctx, service} = this;
    const user_id = ctx.request.user.id;
    const tag_name = ctx.request.body.tag_name;

    let result = await service.topicCollectSvc.listTags(user_id, tag_name);
    ctx.body = {status: 'success', data: result};
    console.timeEnd('listTags');
  }


  /**
   * 展示用户所有标签及标签包含文章的数量+该链接是否已收藏
   * content: 待收藏的文章链接url
   * user_id: 用户id
   */
  async showInfo() {
    console.time('listTags');
    const {ctx, service} = this;
    const original_url = ctx.request.body.original_url;
    const user_id = ctx.request.user.id;

    const collectInfo = await ctx.model.TopicCollect.findOne({original_url, user_id});

    let brief;
    let alreadyTags = [];
    let topic_id;
    let title;
    let is_public = true;
    if (collectInfo) {
      brief = collectInfo.brief || '';
      if (collectInfo.tags) {
        alreadyTags = collectInfo.tags.map((v) => {
          return {name: v}
        });
      }
      topic_id = collectInfo.topic_id;
      title = collectInfo.title;
      is_public = collectInfo.is_public;
    }

    let userAllTags = await service.topicCollectSvc.listTags(user_id);
    ctx.body = {status: 'success', data: {topic_id, title, brief, is_public, alreadyTags, userAllTags}};
    console.timeEnd('listTags');
  }
}

module.exports = CollectApi;
